package com.igeek.boot.controller;

import com.igeek.boot.constant.RedisConstant;
import com.igeek.boot.entity.Assets;
import com.igeek.boot.entity.WmsLog;
import com.igeek.boot.service.IAssetsService;
import com.igeek.boot.service.IWmsLogService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @package com.igeek.boot.controller
 * @Description 任务测试
 * @Author LittlePunk [296526219@qq.ccom]
 * @Version 2022.1
 * @Date 2024/1/11 21:11
 */
@RestController
@Api(tags = "任务接口")
@RequestMapping("/wisdom_factory/task")
public class TaskController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private IWmsLogService wmsLogService;

    @Autowired
    private IAssetsService assetsService;

    @GetMapping("/test")
    public String test() {
        //1.获取当前时间 和  前一天数据
        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String beforeDay = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //2.存入今天Redis中的库存信息  --> 获取当物资的信息，并将信息传入到redis中
        List<Assets> assets = assetsService.findAll();
        for (Assets asset : assets) {
            redisTemplate.opsForList().leftPushAll(RedisConstant.VERIFICATION_ASSET_INVENTORY + today, asset);
        }
        //3.取出前一天的数据
        List<Object> assets1 = redisTemplate.opsForList().range(RedisConstant.VERIFICATION_ASSET_INVENTORY + beforeDay, 0, -1);
        //4.遍历获取前一天的库存信息  将信息转成map存储
        HashMap<String, Integer> beforeMap = new HashMap<>();
        for (Object o : assets1) {
            Assets asset = (Assets) o;
            //按照  名称+类型+货架id作为key
            String key1 = asset.getAssetName() + asset.getAssetType() + asset.getShelfId();
            beforeMap.put(key1, asset.getQuantity());
        }
        //5.遍历当前的库存信息  将信息转成map存储
        HashMap<String, Integer> afterMap = new HashMap<>();
        for (Assets asset : assets) {
            String key = asset.getAssetName() + asset.getAssetType() + asset.getShelfId();
            afterMap.put(key, asset.getQuantity());
        }
        //6.获取入库所有信息并进行遍历 --> 将封装号的数据使用map做加减操作
        List<WmsLog> todayInStock = wmsLogService.findTodayInStock();
        HashMap<String, Integer> todayInStockMap = new HashMap<>();
        for (WmsLog wmsLog : todayInStock) {
            //获取到其中的参数
            String s = wmsLog.getMethodParams();
            //获取订单名  订单类型  订单数量
            Pattern pattern = Pattern.compile("incomingName=([^\"]+), incomingType=([^\"]+), incomingQuantity=([^\\s,]+)");
            Matcher matcher = pattern.matcher(s);
            int startIndex = s.indexOf("shelfID=") + "shelfID=".length();
            int endIndex = s.indexOf(",", startIndex);
            if (endIndex == -1) {
                endIndex = s.indexOf(")", startIndex); // 如果shelfID是最后一个属性，那么找到')'的位置
            }
            String shelfID = s.substring(startIndex, endIndex).trim(); // 去除可能的前后空格
            String incomingName = null;
            String incomingType = null;
            String incomingQuantity = null;
            if (matcher.find()) {
                incomingName = matcher.group(1);
                incomingType = matcher.group(2);
                incomingQuantity = matcher.group(3);
            }
            //将信息填入map集合中
            if (incomingName != null && incomingType != null && incomingQuantity != null) {
                String key = incomingName + incomingType + shelfID;
                todayInStockMap.put(key, Integer.parseInt(incomingQuantity));
            }
        }

        //7，获取出库的所有信息并进行遍历 --> 将封装的数据使用map 做加减操作
        List<WmsLog> todayOutStock = wmsLogService.findTodayOutStock();
        HashMap<String, Integer> todayOutStockMap = new HashMap<>();
        for (WmsLog wmsLog : todayOutStock) {
            //获取到其中的参数
            String s = wmsLog.getMethodParams();
            //获取订单名  订单类型  订单数量
            Pattern pattern = Pattern.compile("outgoingName=([^\"]+), outgoingType=([^\"]+), outgoingQuantity=([^\\s,]+)");
            Matcher matcher = pattern.matcher(s);
            int startIndex = s.indexOf("shelfID=") + "shelfID=".length();
            int endIndex = s.indexOf(",", startIndex);
            if (endIndex == -1) {
                endIndex = s.indexOf(")", startIndex); // 如果shelfID是最后一个属性，那么找到')'的位置
            }
            String shelfID = s.substring(startIndex, endIndex).trim(); // 去除可能的前后空格
            String outgoingName = null;
            String outgoingType = null;
            String outgoingQuantity = null;
            if (matcher.find()) {
                outgoingName = matcher.group(1);
                outgoingType = matcher.group(2);
                outgoingQuantity = matcher.group(3);
            }
            //将信息存入map
            if (outgoingName != null && outgoingType != null && outgoingQuantity != null) {
                String key = outgoingName + outgoingType + shelfID;
                todayOutStockMap.put(key, Integer.parseInt(outgoingQuantity));
            }
        }

        //8.遍历入库的map来进行加操作
        Set<Map.Entry<String, Integer>> entries = todayInStockMap.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
            //当前的key如果beforeMap中存在，就进行添加操作 否则就进行添加操作
            if (beforeMap.containsKey(entry.getKey())) {
                //获取当前的key对应的数量
                int beforeQuantity = beforeMap.get(entry.getKey());
                //获取入库的数量
                int inQuantity = entry.getValue();
                //进行加减操作
                beforeMap.put(entry.getKey(), beforeQuantity + inQuantity);
            } else {
                beforeMap.put(entry.getKey(), entry.getValue());
            }
        }

        //9.遍历出库的map来进行减操作
        Set<Map.Entry<String, Integer>> entries1 = todayOutStockMap.entrySet();
        for (Map.Entry<String, Integer> entry : entries1) {
            //当前的key如果存在beforeMap中就进行减操作
            if (beforeMap.containsKey(entry.getKey())) {
                //获取当前的key对应的数量
                int beforeQuantity = beforeMap.get(entry.getKey());
                //获取出库的数量
                int outQuantity = entry.getValue();
                //进行加减操作
                beforeMap.put(entry.getKey(), beforeQuantity - outQuantity);
            }
        }

        //10.循环判断beforeMap和afterMap中的每个key对应的值是否相等
        // 循环比较两个Map中的键值对
        boolean isEqual = true;
        for (Map.Entry<String, Integer> entry : beforeMap.entrySet()) {
            String key = entry.getKey();
            Integer beforeValue = entry.getValue();
            Integer afterValue = afterMap.get(key);
            if (beforeValue != afterValue) {
                isEqual = false;
                break;  // 如果发现不等的键值对，就跳出循环
            }
        }
        // 输出比较结果
        if (isEqual) {
            return "经审核，今天无异常订单";
        }
        return "出现异常订单，请管理员计时进行审核";
    }
}
